package com.fc.mall.portal.service.impl;

import com.fc.mall.mapper.SysPropertyConfigMapper;
import com.fc.mall.mapper.UmsMemberLevelMapper;
import com.fc.mall.mapper.UmsMemberMapper;
import com.fc.mall.model.*;
import com.fc.mall.model.*;
import com.fc.mall.portal.dao.UmsMemberLevelDao;
import com.fc.mall.portal.model.CommissionMembers;
import com.fc.mall.portal.model.MemberCommission;
import com.fc.mall.portal.service.*;
import com.fc.mall.util.Constants;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.portal.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UmsMemberCommissionServiceImpl implements UmsMemberCommissionService {

    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private SysPropertyConfigService businessConfigService;
    @Autowired
    private UmsMemberUpgradeService memberUpgradeService;
    @Autowired
    private UmsMemberAccountChangeHistoryService memberAccountChangeHistoryService;

    @Autowired
    private UmsMemberAccountService memberAccountService;

    @Autowired
    private UmsMemberLevelDao memberLevelDao;

    @Autowired
    private SysPropertyConfigMapper sysPropertyConfigMapper;

    @Autowired
    private SmsService smsService;

    @Override
    public void handlePurchaseCommission(Long buyerMemberId, Integer totalCommissionAmount, String orderSn)
    {
        UmsMember umsMember = memberMapper.selectByPrimaryKey(buyerMemberId);
        if(umsMember == null)
        {
            return;
        }

        if(totalCommissionAmount == null
                || totalCommissionAmount <= 0)
        {
            return;
        }

        CommissionMembers commissionMembers = null;
        // 获取购买者会员level信息
        if(Constants.MemberLevelType.Member.getValue() == umsMember.getLevelType().intValue())
        {
            // 购物者为普通会员
            commissionMembers = handleMemberCommission(umsMember);
        }
        else if(Constants.MemberLevelType.Agent.getValue() == umsMember.getLevelType())
        {
            // 购物者为代理商，可能是VIP会员，黄金会员或者钻石会员
            commissionMembers = handleAgentCommission(umsMember);
        }
        else if(Constants.MemberLevelType.Partner.getValue() == umsMember.getLevelType())
        {
            // 购物者为代理商合伙人
            commissionMembers = new CommissionMembers();
            commissionMembers.setPartnerMemberId(umsMember.getId());
        }

        // 组装需要分配佣金的会员
        List<MemberCommission> memberCommissionList = null;
        if(commissionMembers != null)
        {
            memberCommissionList = calculateMemberCommissions(commissionMembers, totalCommissionAmount);
        }

        // 保存各自会员的佣金
        if(memberCommissionList != null)
        {
            saveAgentAndPartnerCommission(umsMember, memberCommissionList, orderSn);
        }
    }

    /**
     * 处理购物者为代理商时
     * @param umsMember
     */
    private CommissionMembers handleAgentCommission(UmsMember umsMember)
    {
        CommissionMembers commissionMembers = new CommissionMembers();
        SysPropertyConfigExample example = new SysPropertyConfigExample();
        example.createCriteria().andCodeEqualTo(Constants.SysPropertyConfigName.BUYERSELFCOMMISSION.getName());
        List<SysPropertyConfig> configs =  sysPropertyConfigMapper.selectByExample(example);

        if(null != configs && !configs.isEmpty())
        {
            String value = configs.get(0).getValue();
            if(!StringUtils.isEmpty(value) && value.equals("1"))
            {
                commissionMembers.setFirstAgentMemberId(umsMember.getId());
            }
        }

        if(StringUtils.isEmpty(umsMember.getParentPath()))
        {
            return commissionMembers;
        }
        String[] parentMemberIds = umsMember.getParentPath().split(",");
        if(parentMemberIds.length > 0)
        {
            for (int i = parentMemberIds.length - 1; i >= 0; i--)
            {
                String parentMemberIdStr = parentMemberIds[i];
                if(StringUtils.isEmpty(parentMemberIdStr))
                {
                    continue;
                }
                UmsMember parentMember = memberMapper.selectByPrimaryKey(Long.valueOf(parentMemberIdStr));
                if(parentMember != null)
                {
                    if(Constants.MemberLevelType.Partner.getValue() == parentMember.getLevelType())
                    {
                        commissionMembers.setPartnerMemberId(parentMember.getId());
                        break;
                    }
                    if(Constants.MemberLevelType.Agent.getValue() == parentMember.getLevelType())
                    {
                        if(null == commissionMembers.getFirstAgentMemberId())
                        {
                            commissionMembers.setFirstAgentMemberId(parentMember.getId());
                        }
                        else if(null == commissionMembers.getFirstAgentParentAgentMemberId())
                        {
                            commissionMembers.setFirstAgentParentAgentMemberId(parentMember.getId());
                        }
                    }
                }
            }
        }
        return commissionMembers;
    }

    /**
     * 处理购物者为普通会员时
     * @param umsMember
     */
    private CommissionMembers handleMemberCommission(UmsMember umsMember)
    {
        CommissionMembers commissionMembers = new CommissionMembers();

        String[] parentMemberIds = umsMember.getParentPath().split(",");
        if(parentMemberIds.length > 0)
        {
            for (int i = parentMemberIds.length - 1; i >= 0; i--)
            {
                String parentMemberIdStr = parentMemberIds[i];
                if(StringUtils.isEmpty(parentMemberIdStr))
                {
                    continue;
                }
                UmsMember parentMember = memberMapper.selectByPrimaryKey(Long.valueOf(parentMemberIdStr));
                if(parentMember != null)
                {
                    if(Constants.MemberLevelType.Partner.getValue() == parentMember.getLevelType())
                    {
                        commissionMembers.setPartnerMemberId(parentMember.getId());
                        break;
                    }
                    if(Constants.MemberLevelType.Agent.getValue() == parentMember.getLevelType())
                    {

                        if(commissionMembers.getFirstAgentMemberId() == null)
                        {
                            commissionMembers.setFirstAgentMemberId(parentMember.getId());
                        }
                        else if (commissionMembers.getFirstAgentParentAgentMemberId() == null)
                        {
                            commissionMembers.setFirstAgentParentAgentMemberId(parentMember.getId());
                        }
                    }
                }
            }
        }
        return commissionMembers;
    }

    private List<MemberCommission> calculateMemberCommissions(CommissionMembers commissionMembers, Integer totalCommissionAmount)
    {
        List<MemberCommission> memberCommissionList = new ArrayList<>();
        if(commissionMembers == null)
        {
            return memberCommissionList;
        }

        Integer allotAmount = 0;
        if(commissionMembers.getFirstAgentMemberId() != null)
        {
            UmsMemberLevel memberLevel = memberLevelDao.getMemberLevelByMemberId(commissionMembers.getFirstAgentMemberId());
            if(null == memberLevel || memberLevel.getCommissionFirstRate().intValue() == 0)
            {
                return memberCommissionList;
            }

            Integer refererRate = memberLevel.getCommissionFirstRate();
            MemberCommission memberCommission = new MemberCommission();
            memberCommission.setMemberId(commissionMembers.getFirstAgentMemberId());
            Integer commission = totalCommissionAmount * refererRate / 100;
            memberCommission.setCommission(commission);
            memberCommission.setRate(refererRate);
            memberCommission.setMemberLevelId(memberLevel.getId());
            memberCommissionList.add(memberCommission);
            // 已分配数额
            allotAmount += commission;
        }

        if(commissionMembers.getFirstAgentParentAgentMemberId() != null)
        {
            UmsMemberLevel memberLevel = memberLevelDao.getMemberLevelByMemberId(commissionMembers.getFirstAgentParentAgentMemberId());
            if(null == memberLevel || memberLevel.getCommissionSecondRate().intValue() == 0)
            {
                return memberCommissionList;
            }
            Integer superRefererRate = memberLevel.getCommissionSecondRate();
            MemberCommission memberCommission = new MemberCommission();
            memberCommission.setMemberId(commissionMembers.getFirstAgentParentAgentMemberId());
            Integer commission = totalCommissionAmount * superRefererRate / 100;
            memberCommission.setCommission(commission);
            memberCommission.setRate(superRefererRate);
            memberCommission.setMemberLevelId(memberLevel.getId());
            memberCommissionList.add(memberCommission);
            // 已分配数额
            allotAmount += commission;
        }

        if(commissionMembers.getPartnerMemberId() != null)
        {
            MemberCommission memberCommission = new MemberCommission();
            memberCommission.setMemberId(commissionMembers.getPartnerMemberId());
            memberCommission.setCommission(totalCommissionAmount - allotAmount);

            if(memberCommissionList.isEmpty()) {
                memberCommission.setRate(100);
            }else {
                int hasCommissionRate = 0;
                for (MemberCommission newMemberCommission :memberCommissionList)
                {
                    if(null != newMemberCommission.getRate())
                    {
                        hasCommissionRate += newMemberCommission.getRate();
                    }
                }
                memberCommission.setRate(100-hasCommissionRate);
                memberCommission.setMemberLevelId(5L);
            }
            memberCommissionList.add(memberCommission);
        }

        return memberCommissionList;

    }

    /**
     * 保存购买者的上级代理商和合伙人的佣金
     * @param buggerMember
     * @param memberCommissionList
     */
    private void saveAgentAndPartnerCommission(UmsMember buggerMember, List<MemberCommission> memberCommissionList, String orderNumber)
    {
        if(memberCommissionList != null && !memberCommissionList.isEmpty())
        {
            for(MemberCommission memberCommission : memberCommissionList)
            {
                Integer commission = memberCommission.getCommission() == null ?  0: memberCommission.getCommission();
                // memberUpgradeService.updateMemberUpgradeCondition(memberCommission.getMemberId(), 0, commission);
                memberAccountService.updateTotalAccount(memberCommission.getMemberId(), commission);

                UmsMemberAccountChangeHistory memberAccountChangeHistory = new UmsMemberAccountChangeHistory();
                memberAccountChangeHistory.setFromMemberId(buggerMember.getId());
                memberAccountChangeHistory.setMemberId(memberCommission.getMemberId());
                memberAccountChangeHistory.setAmount(commission.longValue());
                memberAccountChangeHistory.setAccountType(Constants.AccountType.WaitAccount.getValue());
                // 金额变更类型 1->购物佣金 2->提现奖励 3->购物消费(购物抵扣) 4->提现
                memberAccountChangeHistory.setType(Constants.AccountChangeType.ShoppingCommission.getValue());
                memberAccountChangeHistory.setRemark(Constants.AccountChangeType.ShoppingCommission.getDesc());
                memberAccountChangeHistory.setCreateTime(new Date());
                memberAccountChangeHistory.setOrderSn(orderNumber);
                memberAccountChangeHistory.setRate(memberCommission.getRate());
                memberAccountChangeHistory.setMemberLevelId(memberCommission.getMemberLevelId());

                // 存到待发放账户中 并未发到可提现账户中
                memberAccountChangeHistory.setStatus(1);
                memberAccountChangeHistoryService.insertMemberAccountChangeHistory(memberAccountChangeHistory);

                String amount = new BigDecimal(commission).divide(new BigDecimal(100)).setScale(2).toString();
                smsService.incomeNotice(memberCommission.getMemberId(), amount, DateTimeHelper.getStringFromDate(new Date(), DateTimeHelper.PAYLOAD_DATEONLY), buggerMember.getId());
            }
        }
    }
}
